package com.pureut.production.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.domain.OperationProcess;
import com.pureut.production.domain.OperationProcessCenter;
import com.pureut.production.domain.ProcessSheet;
import com.pureut.production.domain.dto.OperationInformationDto;
import com.pureut.production.domain.dto.OperationProcessDto;
import com.pureut.production.domain.vo.OperationInformationVo;
import com.pureut.production.domain.vo.OperationProcessVo;
import com.pureut.production.mapper.OperationInformationMapper;
import com.pureut.production.mapper.OperationProcessMapper;
import com.pureut.production.mapper.ProcessSheetMapper;
import com.pureut.production.service.OperationProcessCenterService;
import com.pureut.production.service.OperationProcessService;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: CM
 * @date: 2023/2/8  14:50
 */
@Service
public class OperationProcessServiceImpl extends ServiceImpl<OperationProcessMapper, OperationProcess> implements OperationProcessService {

    /**
     * 工艺流程
     */
    @Resource
    OperationProcessMapper operationProcessMapper;

    /**
     * 工序信息和工艺流程中间表
     */
    @Resource
    OperationProcessCenterService operationProcessCenterService;


    /**
     * 工序信息
     */
    @Resource
    OperationInformationMapper operationInformationMapper;

    /**
     * 工艺卡信息
     */
    @Resource
    ProcessSheetMapper processSheetMapper;


    /**
     * 新增工艺流程
     *
     * @param operationProcessVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(OperationProcessVo operationProcessVo) {

        //查询当前编码是否存在
        OperationProcess operationProcess1 = operationProcessMapper.selectOne(new QueryWrapper<OperationProcess>().lambda().eq(OperationProcess::getFlowCode, operationProcessVo.getFlowCode()));
        if (operationProcess1 != null) {
            throw new GlobalException("当前流程编码已存在");
        }
        OperationProcess operationProcess = new OperationProcess();
        BeanUtils.copyProperties(operationProcessVo, operationProcess);
        operationProcess.setDeptId(SecurityUtils.getDeptId());
        operationProcess.setCreateTime(new Date());
        operationProcess.setCreateMan(SecurityUtils.getUsername());
        boolean save = save(operationProcess);
        //查询工序信息
        List<OperationInformationVo> list = operationProcessVo.getList();
        if (list.size() < 1) {
           throw new GlobalException("至少选择一个工序");
        }

        List<OperationProcessCenter> arrList = new ArrayList<>();
        if (save) {
            //查询新增工艺流程id
            OperationProcess operationProcess2 = operationProcessMapper.selectOne(new QueryWrapper<OperationProcess>().lambda().eq(OperationProcess::getFlowCode, operationProcessVo.getFlowCode()));

            for (OperationInformationVo operationInformationVo : list) {
                OperationProcessCenter operationProcessCenter = new OperationProcessCenter();
                operationProcessCenter.setInformationId(operationInformationVo.getId());
                operationProcessCenter.setProcessId(operationProcess2.getId());
                arrList.add(operationProcessCenter);
            }
            operationProcessCenterService.saveBatch(arrList);
        } else {
            throw new GlobalException("新增失败");
        }

        return save;
    }

    /**
     * 工艺流程修改
     *
     * @param operationProcessVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(OperationProcessVo operationProcessVo) {

        OperationProcess operationProcess1 = operationProcessMapper.selectById(operationProcessVo.getId());

        //删除当前的工艺流程表和中间表
        boolean i = removeById(operationProcessVo.getId());

        if (i) {
            operationProcessCenterService.remove(new QueryWrapper<OperationProcessCenter>().lambda().eq(OperationProcessCenter::getProcessId, operationProcessVo.getId()));
            OperationProcess operationProcess = new OperationProcess();
            BeanUtils.copyProperties(operationProcessVo, operationProcess);
            operationProcess.setFlowCode(operationProcess1.getFlowCode());
            operationProcess.setDeptId(SecurityUtils.getDeptId());
            operationProcess.setCreateTime(new Date());
            operationProcess.setCreateMan(SecurityUtils.getUsername());
            boolean save = save(operationProcess);
            //查询工序信息
            List<OperationInformationVo> list = operationProcessVo.getList();

            List<OperationProcessCenter> arrList = new ArrayList<>();
            if (save) {
                for (OperationInformationVo operationInformationVo : list) {
                    OperationProcessCenter operationProcessCenter = new OperationProcessCenter();
                    operationProcessCenter.setInformationId(operationInformationVo.getId());
                    operationProcessCenter.setProcessId(operationProcess.getId());
                    arrList.add(operationProcessCenter);
                }
                operationProcessCenterService.saveBatch(arrList);
            }
        } else {
            throw new GlobalException("修改失败");
        }

        return i;
    }

    /**
     * 工艺流程删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean remove(String ids) {
        //将ids根据逗号拆分成数组
        List<String> idStr = Arrays.asList(ids.split(","));

        //删除中间表中的数据
        for (String id : idStr) {

            //查询当前的工艺流程是否关联了工艺卡
            List<ProcessSheet> processSheetList = processSheetMapper.selectList(new QueryWrapper<ProcessSheet>().lambda().eq(ProcessSheet::getFlowId, id));

            if (processSheetList.size()>0){
                throw new GlobalException("此工工艺流程已关联工艺卡,不可删除");
            }

            boolean remove = operationProcessCenterService.remove(new QueryWrapper<OperationProcessCenter>().lambda().eq(OperationProcessCenter::getProcessId, id));

        }

        return removeBatchByIds(idStr);

    }

    /**
     * 工艺流程列表查询
     *
     * @param operationProcessVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<OperationProcessDto> getList(OperationProcessVo operationProcessVo) {
        List<OperationProcessDto> processList = operationProcessMapper.getProcessList(operationProcessVo);

        List<SysDictData> statusArray = DictUtils.getDictCache("quality_production_level");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (OperationProcessDto operationProcessDto : processList) {
            operationProcessDto.setProductionLevle(operationProcessDto.getProductionLevle());
            operationProcessDto.setProductionLevleDict(statusMap.get(operationProcessDto.getProductionLevle()));
        }
        return processList;
    }

    /**
     * 工艺流程查看
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationProcessDto view(Long id) {
        OperationProcess operationProcess = operationProcessMapper.selectById(id);

        //dto出参
        OperationProcessDto operationProcessDto = new OperationProcessDto();
        operationProcessDto.setId(id);
        operationProcessDto.setFlowCode(operationProcess.getFlowCode());
        operationProcessDto.setFlowName(operationProcess.getFlowName());
        operationProcessDto.setProductionLine(operationProcess.getProductionLine());

        List<SysDictData> statusArray = DictUtils.getDictCache("quality_production_level");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        operationProcessDto.setProductionLevle(operationProcess.getProductionLevle());
        operationProcessDto.setProductionLevleDict(statusMap.get(operationProcess.getProductionLevle()));

        //查询中间表中的工序信息id
        List<Long> idList = operationProcessCenterService.getId(id);

        List<OperationInformationDto> operationInformations = operationInformationMapper.selectBatchOperationIds(idList);
        for (OperationInformationDto operationInformation : operationInformations) {
            operationInformation.setProductionLevelDict(statusMap.get(operationProcess.getProductionLevle()));
        }

        operationProcessDto.setList(operationInformations);

        return operationProcessDto;
    }

    /**
     * 通过线别查出工艺流程列表
     *
     * @param productionLineDict
     * @return
     */
    @Override
    public List<OperationProcessDto> getLine(String productionLineDict) {
        return operationProcessMapper.getLine(productionLineDict);
    }


}
